package cn.hxzy.servlet.admin;

import cn.hxzy.entity.User;
import cn.hxzy.service.UserService;
import cn.hxzy.util.Md5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("WEB-INF/jsp/admin/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String loginName = req.getParameter("loginName");
            req.setAttribute("loginName", loginName);
            String loginPassword = req.getParameter("loginPassword");
            String s = Md5Util.MD5(loginPassword);
            User user = userService. login(loginName, s);
            if (user != null) {
                req.getSession().setAttribute("loginUser", user);
                resp.sendRedirect("adminIndex");
                return;
            }
//            req.setAttribute("message", "账号或密码错误");
            req.getRequestDispatcher("WEB-INF/jsp/admin/login.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
